#include "emb_mem.h"

#define EMB_MEM_ALIGN_SIZE 4

void emb_mem_init(emb_mem_ctrl_t *Ctrl,uint8_t* Buf,uint16_t BufSize)
{
    EMB_PORT_ASSERT(Ctrl!=NULL&&Buf!=NULL);

    Ctrl->Start = Buf;
    Ctrl->Used = 0;

#if EMB_CONF_MEM_DEBUG_ENABLE > 0
    Ctrl->Size = BufSize;
    EMB_PORT_DEBUG("mem size is %d\r",BufSize);
#endif
}

void* emb_mem_alloc(emb_mem_ctrl_t *Ctrl,size_t Size)
{
    void *ptr = NULL;
    EMB_PORT_ASSERT(Ctrl != NULL);

#if EMB_CONF_MEM_DEBUG_ENABLE > 0
    EMB_PORT_DEBUG("size of mem unsued is %d\r",Ctrl->Size-Ctrl->Used);
    if ((Ctrl->Used + Size) > Ctrl->Size)
    {
        return NULL;
    }
#endif

    ptr=Ctrl->Start+Ctrl->Used;
    Ctrl->Used += Size;
    return ptr;
}

void emb_mem_free(emb_mem_ctrl_t *Ctrl)
{
    EMB_PORT_ASSERT(Ctrl != NULL);
    Ctrl->Used = 0;
}